(function ($) {
    //默认参数
    var defaluts = {
        searchName: '.ySearchSelect'
    };

    $.fn.extend({
        "ySearchSelect": function (options) {
            defaluts.searchName = options;
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                init(opts);
            });

        }
    });
    //初始化插件
    let productInfo = [];
    function init(o){
        $(document).click(function(){
            var thin = this;
            $(".ySearchSelect table").hide();
            $(".ySearchSelect .input-text").hide();
            $(".ySearchSelect .layui-form.layui-border-box.layui-table-view").hide();
            $(".ySearchSelect i.layui-edge").removeClass("select");
        });

        $(o.searchName+" .layui-input").click(function(event){
            //阻止document点击事件
            event.stopPropagation();
            if($(this).siblings(".input-text").length <= 0){
                var str = '<div class="input-text">'+
                    '<input type="text" name="" placeholder="输入关键字" class="layui-input">'+
                    '</div>';
                $(o.searchName).append(str);
            }
            if($(this).siblings("table").css("display") == "none"){
                var ids = $(o.searchName).attr("data-id");
                table.render({
                    elem: '#productcodeselect_'+ids,
                    id: 'productcodeselecttableid_'+ids,
                    data: productInfo,
                    url:'initStock/add/getProductInfo',
                    cols: [[
                        {field: 'productCode', width: 220, title: '产品编码'},
                        {field: 'specificationCode', width: 120, title: '规格编码'},
                        {field: 'productCname', width: 120, title: '中文名称'},
                        {field: 'productEname', width: 120, title: '英文名称'},
                        {field: 'directoryName', width: 120, title: '产品目录'}
                    ]],
                    height: 200
                });
                table.on('row(productcodeselecttable_'+ids+')', function(obj){
                    let data = obj.data;
                    let tableData = table.cache["storageproductstableid"];
                    $.each(tableData,function(index,value){
                        if(value.tempId == ids){
                            data.tempId = ids;
                            //数量（默认为零）
                            data["amount"] = 0;
                            //产品编码
                            data["productNo"] = data.productCode;
                            //规格编码
                            data["specNo"] = data.specificationCode;
                            //规格说明
                            data["normExplain"] = data.specificationExplanation;
                            //产品中文名称
                            data["chineseName"] = data.productCname;
                            //产品英文名称
                            data["englishName"] = data.productEname;
                            //中文描述
                            data["chineseDesc"] = data.productCdesc;
                            //英文描述
                            data["englishDesc"] = data.productEdesc;
                            //产品单位
                            data["unit"] = data.productUnit;
                            //颜色
                            data["colour"] = data.color;
                            //单价
                            data["costPrice"] = data.unitPrice;
                            //毛重
                            data["grossWeight"] = data.grossWeight;
                            //净重
                            data["netWeight"] = data.netWeight;
                            //体积
                            data["volume"] = data.bulk;
                            //外包装长
                            data["outPackLength"] = data.outerPackingLong;
                            //外包装宽
                            data["outPackWidth"] = data.outerPackingWide;
                            //外包装高
                            data["outPackHeight"] = data.outerPackingHeight;
                            data["price"] = 0;
                            data["otherPrice"] = 0;
                            data["priceSubtotal"] = 0;

                            tableData[index] = data;
                        }
                    });
                    table.reload('storageproductstableid',{data:tableData});
                });
                $(this).siblings("i").addClass("select");
                $(this).siblings("table").show();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").show();
                $(this).siblings(".input-text").show();
            }else{
                $(this).siblings("i").removeClass("select");
                $(this).siblings("table").hide();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").hide();
                $(this).siblings(".input-text").hide();
            }
            $(o.searchName+" .input-text input").focus();
            $(o.searchName+" .input-text").width(605);

            //键盘监听事件
            $(o.searchName+" .input-text input").keyup(function(event){
                if(event.keyCode != 38 && event.keyCode != 40 && event.keyCode == 13){
                    ySearchSelectMate($(this).val(),o.searchName);
                }
            });
        });
    }

    //匹配搜索，不匹配则隐藏。
    function ySearchSelectMate(value,name){
        value = $.trim(value.toString()); // 去掉两头空格
        let ids = $(name).attr("data-id");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function(index, values){
            if(values.tempId == ids){
                tableData[index]["productCode"] = value;
                //$(".value_"+values.tempId).html(value);
            }
        });
        //模糊查询表格并刷新
        table.reload('productcodeselecttableid_'+ids,{where: {
                info:value
            }});
    }
})(window.jQuery);
let form = layui.form, laydate = layui.laydate, upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id"), types = getQueryVariable("types");

layui.use(['tableEdit'], function () {
    let layer = layui.layer;
//签约日期默认当天
laydate.render({
    elem: '#signTime',
    type: 'date',
    value: new Date(),
});

//联系人
let contactPersonList = [];
//交货日期
lay('#deliverDate').each(function () {
    laydate.render({
        elem: '#deliverDate',
        //监听日期被切换
        done: function(value, date){
            //产品明细数据
            let detailList = table.cache["storageproductstableid"];
            for(let i in detailList){
                detailList[i]["requestDeliveryDate"] = value;
            }
            table.reload('storageproductstableid',{data:detailList});
        }
    });
});

//签约单位
let complaintUnit = [];
$.ajax({
    url: "company/getAllMakerUnit",
    success: function (res) {
        if (res.status == 200) {
            complaintUnit = res.data;
            $.each(res.data, function (index, item) {
                if(item){
                    $("#companyCode").append(new Option(item.name, item.code));
                }
            });
            form.render('select');
        } else {
            layer.msg(res.msg, {icon: 5});
        }
    }
});
//供应商
let supplierList = [];
//素材供应商
let materialSupplierList = [];
$.ajax({
    url: "purchase/getFilterCustomer2List",
    success: function (res) {
        if (res.status == 200) {
            supplierList = res.data;
            materialSupplierList = res.data;
            materialSupplierList.push({name: "无", code:"无"})
            $.each(res.data, function (index, item) {
                $("#supplierCode").append(new Option(item.name, item.code));
            });
            form.render('select');
        } else {
            layer.msg(res.msg, {icon: 5});
        }
    }
});
function selectAddress(code){
    $.ajax({
        type: 'POST',
        url: "purchase/selectSupplierByCode/"+code,
        dataType: "json",
        success: function (res) {
            let accountPeriod = "";
            if (res.status == 200) {
                accountPeriod = res.data.accountPeriod;
            } else {
                layer.msg("付款账期、交货地点 "+res.msg, {icon: 3});
            }
            form.val("editor-form", {
                "deliverAddress": "上海码头",
                "paymentTime": accountPeriod,
            })
            //设置联系人
            setContactPerson(code);
        }
    });

}

//设置联系人
function setContactPerson(code){
    $.ajax({
        type: 'GET',
        url: "customer2contact/getContactPerson",
        data: {"company":code},
        dataType: "json",
        async:false,
        success: function (res) {
            if (res.status == 200) {
                if(res.data.length>0){
                    contactPersonList = res.data;
                    //清空下拉框值
                    $('#contactPerson').empty();
                    let isDefaultName = "";
                    let isDefaultEmail = "";
                    for(let i in contactPersonList){
                        if(contactPersonList[i]["isDefault"] === 1){
                            isDefaultName = contactPersonList[i].name;
                            isDefaultEmail = contactPersonList[i].email;
                        }
                        $('#contactPerson').append(new Option(contactPersonList[i].name, contactPersonList[i].name));
                    }
                    //选中默认联系人
                    $('#contactPerson').val(isDefaultName);
                    $('#contactEmail').val(isDefaultEmail);
                    form.render('select');
                }else{
                    layer.msg("暂无联系方式", {icon: 3});
                }
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

//监听联系人下拉框
form.on("select(contactPerson)", function(data){
    if(data.value === ""){
        $('#contactEmail').val("");
        return;
    }
    for(let i in contactPersonList){
        if(data.value == contactPersonList[i].name){
            $('#contactPerson').val(contactPersonList[i].name);
            $('#contactEmail').val(contactPersonList[i].email);
            break;
        }
    }
});

let loginUserCode = user.code;//当前登录用户编码
let executorList = [];
$.ajax({
    url:"user/getAllUserNameAndCode",
    success:function(res){
        if(res.status == 200){
            executorList = res.data;
            $.each(res.data, function (index, item) {
                $("#executor").append(new Option(item.name, item.code));
                $("#salesman").append(new Option(item.name, item.code));
            });
            if (id != "") {
                queryById();
            }else{
                $("#executor").val(loginUserCode);
                $("#whetherCreditGuarantee").val(0);
                $("#creditGuaranteeAmount").val(0);
                form.render();
            }
            $("#invoiceStatus").val(1);//默认开票：是
            form.render('select');
        }else{
            layer.msg(res.msg, {icon: 5});
        }
    }
});

let currencyList = [];
//获取币种
$.ajax({
    url:"receivePayment/getCurrencyInfo",
    success:function(res){
        let rmbCode = ""
        if(res.status == 200){
            currencyList = res.data;
            let rmbRate = 0;
            for(let i in res.data){
                if(res.data[i].englishName == "USD"){
                    //美元->人民币 汇率
                    rmbRate = res.data[i].exchangeRate;
                }
                if(res.data[i].englishName == "RMB"){
                    //人民币编码
                    rmbCode = res.data[i].code;
                    //人民币
                    rmbName = res.data[i].name;
                    //美元汇率
                    $("#usdRate").val(res.data[i].exchangeRate);
                }
                $('#currency').append(new Option(res.data[i].name, res.data[i].code));
            }
            if(rmbCode.length > 0){
                //默认RMB选中
                $('#currency').val(rmbCode);
                $('#rmbRate').val(rmbRate);
            }
            form.render('select');
        }
    }
});
let paymentTypeList = getdictionary(5, 17);//付款类型
let colourList = getdictionary(6, 41);//颜色
let unitList = getdictionary(6, 42);//单位
let bankList = [];//银行列表


for (let i in paymentTypeList) {
    $('#paymentType').append(new Option(paymentTypeList[i].name, paymentTypeList[i].code));
}

lay('.starttime').each(function () {
    laydate.render({
        elem: this
    });
});

form.render('select');


let productList = [];
let fileList = [];
let wjCatalogCode = "purchase";//文件编码
let logList = [];

//表单初始值，修改时调用
if (id != "") {
    form.val("editor-form", {
        "executorCode": "进入修改",
    })
}

//监听提交
form.on('submit(form-element)', function (data) {
    let indexSl = 0;//未填写 错误行数
    let storageProductsData = table.cache["storageproductstableid"];
    let tmparr=[]
    $.each(storageProductsData, function (index, value) {
        if (typeof (storageProductsData[index]["specNo"]) == "undefined" || storageProductsData[index]["specNo"] == "") {
            layer.msg("产品信息：第" + (index + 1) + "条规格编码不能为空");
            indexSl++;
            return false;
        }
        //素材供应商不能为空
        if (typeof (storageProductsData[index]["materialSupplier"]) == "undefined" || storageProductsData[index]["materialSupplier"] === "") {
            layer.msg("产品信息：第" + (index + 1) + "条素材供应商不能为空");
            indexSl++;
            return false;
        }
        if (isEmpty(storageProductsData[index]["costPrice"])) {
            tmparr.push(index+1)
        }
    });
    if(tmparr.length){
       //let onoff= layer.confirm("产品信息：第" + (tmparr.join(",")) + "条产品单价不能为空");
        layer.confirm("产品单价存在为零的记录，是否继续？",
            confirmInfo(3,6),
            function (index) {
                if (indexSl == 0) {
                    submitData(data);
                }
                layer.close(index);
                return false;
            });
        return false;

    }

    if (indexSl == 0) {
        submitData(data);
    }
    return false;
});

function submitData(data){
    $("#purchaseType").removeAttr("disabled");
    let reqData = data.field;
    let productCache = table.cache["storageproductstableid"];
    reqData["productList"] = productCache;
    reqData["fileList"] = fileList;
    let flag = false;
    if (id == "") {
        flag = insert(reqData);
    } else {
        reqData.id = id;
        flag = update(reqData);
    }
    $("#purchaseType").attr("disbaled",true);
    if (flag) {
        setTimeout(function () {
            //保存成功则刷新提交过来的界面 并关闭此页面
            parent.detab("views/jsp/ExportBusiness/procurement.jsp");
            parent.intab("views/jsp/ExportBusiness/procurement.jsp", "采购")
            parent.detab("views/jsp/ExportBusiness/tpl/newSamplePurchase.jsp?types="+types);
            parent.detab("views/jsp/ExportBusiness/tpl/newSamplePurchase.jsp" + (id == '' ? '' : '?id=' + id+"&types="+types));
        }, 1000);
    }
}

//--产品信息
table.render({
    elem: '#storageproducts',
    id: 'storageproductstableid',
    data: productList,
    toolbar: '#storageproductstoolbar',
    totalRow: true,
    cellMinWidth: 120,
    cols: [[
        {checkbox: true, fixed: true},
        {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
        // {field: 'productImg', title: '图片', width: 120, align: 'center', templet: '#imgTpl'},
        {field: 'salesContractNo', title: '销售合同号'},
        {field: 'chineseName', title: '中文名称',style:"overflow:hidden" },
        {field: 'productNo', title: '产品编码',width: 220, templet: '#productcodeselect'},
        {field: 'specNo', title: '规格编码', edit: 'text'},
        {field: 'normExplain', title: '规格说明', edit: 'text',style:"overflow:hidden"},
        {field: 'chineseDesc', title: '中文描述', edit: 'text',style:"overflow:hidden"},
        {field: 'englishDesc', title: '英文描述', edit: 'text',style:"overflow:hidden"},
        {field: 'unit', title: '单位',
            templet: function(data) {
                let name = "";
                $.each(unitList, function(index, item) {
                    if (data.unit==item.code){
                        name = item.name;
                        return ;
                    }
                });
                if(data.unit){
                    if(name==""){
                        name = data.unit;
                    }
                }
                return name;
            },
        },
        {field: 'colour', title: '颜色', edit: 'text'},
        {field: 'materialSupplier', title: '素材供应商', width: 240, templet: '#materialSupplierSelect'},
        {field: 'costPrice', title: '产品单价', edit: 'text', totalRow: true,
            templet: function(d){
                let costPrice = d.costPrice?d.costPrice:0;
                return Number(costPrice).toFixed(6)
            }
        },
        {field: 'taxedCostPrice', title: '产品-含税单价', hide: true, totalRow: true,
            templet: function(d){
                let taxedCostPrice = d.taxedCostPrice?d.taxedCostPrice:0.0000;
                return Number(taxedCostPrice).toFixed(4)
            }
        },
        {field: 'untaxedCostPrice', title: '产品-未税单价', hide: true, totalRow: true,
            templet: function(d){
                let untaxedCostPrice = d.untaxedCostPrice?d.untaxedCostPrice:0.0000;
                return Number(untaxedCostPrice).toFixed(4)
            }
        },
        {field: 'amount', title: '数量', edit: 'text', totalRow: true,
            templet: function(d) {
                return d.amount?Number(d.amount).toFixed(2):0.00;
            }},
        {field: 'price', title: '采购成本', totalRow: true,
            templet: function(d) {
                let costPrice = d.costPrice?d.costPrice:0.00;
                let otherPrice = d.otherPrice?d.otherPrice:0.00;
                let amount = d.amount?d.amount:0.00;
                let price = 0.0000;
                if(amount==0){
                    price = costPrice;
                }else{
                    price = (Number(costPrice)+Number(otherPrice/amount)).toFixed(6);
                }
                return price;
            }
        },
        {field: 'otherPrice', title: '其他费用', edit: 'text', totalRow: true,
            templet: function(d){
                let otherPrice = d.otherPrice?d.otherPrice:0.0000; return Number(otherPrice).toFixed(4);
            }
        },
        {field: 'otherDesc', title: '费用备注', edit: 'text'},
        {field: 'priceSubtotal', title: '成本金额小计', totalRow: true},
        {field: 'requestDeliveryDate', title: '要求交货日期',
            templet:function(d){
                return '<input type="text" value="'+layui.util.toDateString(d.requestDeliveryDate,"yyyy-MM-dd")+'"  class="layui-input layui-input-date">';
            }
        },
        {field: 'grossWeight', title: '毛重',
            templet: function(d){
                let grossWeight = d.grossWeight?d.grossWeight:0.00; return Number(grossWeight).toFixed(2);
            }
        },
        {field: 'grossSubtotal', title: '毛重小计',
            templet: function(d) {
                let grossSubtotal = d.grossSubtotal?d.grossSubtotal:0.00; return Number(grossSubtotal).toFixed(2);
            }},
        {field: 'netWeight', title: '净重', edit: 'text',
            templet: function(d) {
                let netWeight = d.netWeight?d.netWeight:0.00; return Number(netWeight).toFixed(2);
            }},
        {field: 'netSubtotal', title: '净重小计', edit: 'text',
            templet: function(d) {
                let netSubtotal = d.netSubtotal?d.netSubtotal:0.00; return Number(netSubtotal).toFixed(2);
            }},
        {field: 'volume', title: '体积', edit: 'text',
            templet: function(d) {
                let volume = d.volume?d.volume:0.00; return Number(volume).toFixed(2);
            }
        },
        {field: 'trayNumber', title: '托数', edit: 'text',
            templet: function(d) {
                let trayNumber = d.trayNumber?d.trayNumber:0.00; return Number(trayNumber).toFixed(2);
            }
        },
        {field: 'trayCapacity', title: '每托量', edit: 'text',
            templet: function(d) {
                let trayCapacity = d.trayCapacity?d.trayCapacity:0.00; return Number(trayCapacity).toFixed(2);
            }
        },
        {field: 'numberOfPiece', title: '箱数', edit: 'text', totalRow: true,
            templet: function(d) {
                let numberOfPiece = d.numberOfPiece?d.numberOfPiece:0.00; return Number(numberOfPiece).toFixed(2);
            }
        },
        {field: 'qty', title: '每箱数量', edit: 'text', totalRow: true, totalRowType:'double',
            templet: function(d) {
                let qty = d.qty?d.qty:0.00; return Number(qty).toFixed(2);
            }
        },
        {field: 'payTime', title: '付款账期', edit: 'text'},
        {field: 'untaxedPrice', title: '未税单价', style:"overflow:hidden", totalRow: true,
            templet: function(d){
                let untaxedPrice = d.untaxedPrice?d.untaxedPrice:0.0000; return Number(untaxedPrice).toFixed(4);
            }
        },
        {field: 'untaxedPriceSubtotal', title: '未税金额小计', style:"overflow:hidden", totalRow: true,
            templet: function(d){
                let untaxedPriceSubtotal = d.untaxedPriceSubtotal?d.untaxedPriceSubtotal:0.00; return Number(untaxedPriceSubtotal).toFixed(2);
            }
        },
        {field: 'platformInquiryOrderNumber', title: '平台询价单号', style:"overflow:hidden", totalRow: true,
            templet: function(d){
                let platformInquiryOrderNumber = d.platformInquiryOrderNumber?d.platformInquiryOrderNumber:0.00; return Number(platformInquiryOrderNumber).toFixed(2);
            }
        },
        {fixed: 'right', title: '操作', width: 80, align: 'center', toolbar: '#productsEditor'},
    ]],
    page: false,
    limit: Number.MAX_VALUE,
    height: 440,
    done: function (res, curr, count) {
        $(".layui-table select").parent(".layui-table-cell").css("overflow","visible")
        $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
        $(".layui-input-date").each((i,e)=>{
            laydate.render({
                elem:e,
                format: 'yyyy-MM-dd',
                type: 'date',
                trigger: 'click',
                theme: '#393D49',
                calendar: true,
                done(data){
                    let tableData = table.cache["storageproductstableid"];
                    tableData[i]["requestDeliveryDate"] = data;
                    table.reload('storageproductstableid',{data:tableData});
                }
            });
        })
        //素材供应商
        for(let i in materialSupplierList){
            $(".materialSupplier").append("<option value=\"" + materialSupplierList[i].name + "\">" + materialSupplierList[i].name + "</option>");
        }
        //合计采购成本、成本金额小计
        let priceSum = 0;
        layui.each(res.data, function (index, d) {
            let costPrice = d.costPrice ? d.costPrice : 0.00;
            let otherPrice = d.otherPrice ? d.otherPrice : 0.00;
            let amount = d.amount ? d.amount : 0.00;
            let price = 0.0000;
            if (amount == 0) {
                price = Number(costPrice);
            } else {
                price = (Number(costPrice) + Number(otherPrice / amount)).toFixed(6);
            }
            priceSum = (Number(priceSum) + Number(price)).toFixed(6);
        })
        this.elem.next().find('.layui-table-total td[data-field="price"] .layui-table-cell').text(priceSum);
        $("#purchaseType").val(types)
        let purchaseTotalPrice = 0;
        let earnestRate = $("#earnestRate").val()==""?0:$("#earnestRate").val();//定金比例
        let earnestMoney = $("#earnestMoney").val()==""?0:$("#earnestMoney").val();//定金金额
        let isTaxIncluded = $("#taxIncluded").val()==""?0:Number($("#taxIncluded").val());//是否含税  1 含税  2 不含税
        let modulus = 1;//含税系数
        if(isTaxIncluded==1){
            modulus=1.13
        }

        let salesContractNos = $("#salesContractNo").val();//销售合同号
        if(salesContractNos!=""){
            salesContractNos+=",";
        }
        if(res.data.length>0){
            let creditGuaranteeAmount = res.data[0].creditGuaranteeAmount;
            let modeOfTrade = res.data[0].modeOfTrade;
            if(!isEmpty(modeOfTrade)){
                $("#modeOfTrade").val(modeOfTrade);
            }
            let purchaseOrderNo = $("#purchaseOrderNo").val();
            if(!purchaseOrderNo){
                form.val("editor-form", {
                    "purchaseOrderNo": res.data[0].salesContractNo,
                })
            }
            let salesmanVal = res.data[0].salesmanCode?res.data[0].salesmanCode:$("#salesman").val();
            $("#salesman").val(salesmanVal);
            let customerLevelCode = res.data[0].customerLevelCode?res.data[0].customerLevelCode:$("#customerLevelCode").val();
            $("#customerLevelCode").val(customerLevelCode);
            let customerLevelName = res.data[0].customerLevelName?res.data[0].customerLevelName:$("#customerLevelName").val();
            $("#customerLevelName").val(customerLevelName);

            let remark = $("#remark").val();
            if(!remark){
                form.val("editor-form", {
                    "remark": res.data[0].importRemark,
                })
            }

            for (let i in colourList) {
                $('.colourSelect').append(new Option(colourList[i].name, colourList[i].code));
            }
            for (let i in unitList) {
                $('.unitSelect').append(new Option(unitList[i].name, unitList[i].code));
            }
            let paymentTime = $("#paymentTime").val()==""?"":$("#paymentTime").val();//付款账期

            let signingName = '';
            let bankName = '';
            let priceSubtotalSum = 0;
            for (let i = 0; i < res.data.length; i++) {
                let tempId = res.data[i].tempId!=undefined?res.data[i].tempId:i;
                let classs = ".y_" + tempId;
                $(classs).ySearchSelect(classs);
                //素材供应商
                let materialSupplier = res.data[i].materialSupplier;
                if(!isEmpty(materialSupplier)){
                    $("#materialSupplier_" + tempId).val(materialSupplier);
                    res.data[i]["materialSupplier"] = materialSupplier;
                }
                res.data[i].tempId = tempId;
                if(res.data[i].signingCode){
                    if(res.data[i].signingName){
                        if(res.data[i].signingName!=signingName){
                            let isExist = false;
                            $.each(complaintUnit,function (index,item) {
                                if(item.code==res.data[i].signingCode){
                                    isExist = true;
                                    return;
                                }
                            })
                            if(!isExist){
                                complaintUnit.push({code:res.data[i].signingCode,name:res.data[i].signingName})
                            }
                            signingName = res.data[i].signingName;
                        }
                    }
                }

                if(res.data[i].bankCode){
                    if(res.data[i].bankName){
                        if(res.data[i].bankName!=bankName){
                            let isExist = false;
                            $.each(bankList,function (index,item) {
                                if(item.code==res.data[i].bankCode){
                                    isExist = true;
                                    return;
                                }
                            })
                            if(!isExist){
                                bankList.push({code:res.data[i].bankCode,name:res.data[i].bankName})
                            }
                            bankName = res.data[i].bankName;
                        }
                    }
                }

                selectBlueprintFileByCode(res.data[i].productNo, res.data[i].specNo);
                //销售合同号
                if(res.data[i].salesContractNo!=undefined){
                    if(salesContractNos.indexOf(res.data[i].salesContractNo) == -1){
                        salesContractNos += res.data[i].salesContractNo+",";
                    }
                }
                $("#colour_" + tempId).val(res.data[i].colour);
                $("#unit_" + tempId).val(res.data[i].unit);
                if(res.data[i].amount>0){
                    let price = 0.0000;
                    if(res.data[i].amount==0){
                        price = res.data[i].costPrice;
                    }else{
                        price = (Number(res.data[i].costPrice)+Number(res.data[i].otherPrice/res.data[i].amount)).toFixed(6);
                    }
                    res.data[i].price = Number(price).toFixed(6);
                    let priceSubtotal = (price*res.data[i].amount).toFixed(2);
                    res.data[i].priceSubtotal = priceSubtotal;
                    priceSubtotalSum = (Number(priceSubtotalSum) + Number(priceSubtotal)).toFixed(2);
                    purchaseTotalPrice += res.data[i].priceSubtotal*1;//采购总额
                    //未税金额
                    res.data[i].untaxedPrice = (price/modulus).toFixed(4);
                    res.data[i].untaxedPriceSubtotal = (res.data[i].amount*res.data[i].untaxedPrice).toFixed(4);
                    if(res.data[i].trayCapacity>0){
                        res.data[i].trayNumber = res.data[i].amount/res.data[i].trayCapacity;
                    }else if(res.data[i].trayNumber>0){
                        res.data[i].trayCapacity = res.data[i].amount/res.data[i].trayNumber;
                    }
                    if(res.data[i].qty>0){
                        res.data[i].numberOfPiece = res.data[i].amount/res.data[i].qty;
                    }else if(res.data[i].numberOfPiece>0){
                        res.data[i].qty = res.data[i].amount/res.data[i].numberOfPiece;
                    }
                }else{
                    res.data[i].trayNumber = res.data[i].trayCapacity = 0.00;
                    res.data[i].qty = res.data[i].numberOfPiece = 0.00;
                }

                res.data[i].grossSubtotal = res.data[i].amount*res.data[i].grossWeight;
                res.data[i].netSubtotal = res.data[i].amount*res.data[i].netWeight;

                res.data[i].payTime = paymentTime;
                let $tr = $('#storageproducts').next().find('tbody tr').eq(i);
                let updateList = [
                    'price',
                    'priceSubtotal',
                    'untaxedPrice',
                    'untaxedPriceSubtotal',
                    'trayCapacity',
                    'trayNumber',
                    'numberOfPiece',
                    'qty',
                    'grossSubtotal',
                    'netSubtotal',
                    'payTime',
                ];
                updateList.forEach(function (e) {
                    $tr.find(`[data-field="${e}"] div`).text(res.data[i][e]?res.data[i][e]:'');
                })
            }
            this.elem.next().find('.layui-table-total td[data-field="priceSubtotal"] .layui-table-cell').text(priceSubtotalSum);

            if (salesContractNos.indexOf(",")!=-1){
                salesContractNos=salesContractNos.substring(0,salesContractNos.length-1);
            }
        }
        if(purchaseTotalPrice>0){
            earnestMoney = (purchaseTotalPrice*earnestRate/100).toFixed(4);
        }else if(purchaseTotalPrice>0 && earnestMoney>0){
            earnestRate = (earnestMoney/purchaseTotalPrice*100).toFixed(4);
        }

        form.val("editor-form", {
            "purchaseTotalPrice": purchaseTotalPrice.toFixed(2),
            "earnestRate": earnestRate,
            "earnestMoney": earnestMoney,
            "salesContractNo": salesContractNos,
        });
        //重载签约公司和银行
        reloadCBSelect();
        form.render('select');
    }
});

function productTableReload(){
    table.reload('storageproductstableid',{
        data:table.cache.test,
        totalRow: true,
    })
}

table.on('edit(storageproductstable)', function (obj) {
    let old = $(this).prev().text();//旧值
    //判断数据类型
    if ((obj.field == "amount" ||
        obj.field == "price" ||
        obj.field == "priceSubtotal" ||
        obj.field == "costPrice" ||
        obj.field == "otherPrice" ||
        obj.field == "untaxedPrice" ||
        obj.field == "untaxedPriceSubtotal") && !isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);
        if(obj.field == "amount"){
            obj.update({
                amount:old,
            })
        }
        if(obj.field == "price"){
            obj.update({
                price:old,
            })
        }
        if(obj.field == "priceSubtotal"){
            obj.update({
                priceSubtotal:old,
            })
        }
        if(obj.field == "costPrice"){
            obj.update({
                costPrice:old,
            })
        }
        if(obj.field == "otherPrice"){
            obj.update({
                otherPrice:old,
            })
        }
        if(obj.field == "untaxedPrice"){
            obj.update({
                untaxedPrice:old,
            })
        }
        if(obj.field == "untaxedPriceSubtotal"){
            obj.update({
                untaxedPriceSubtotal:old,
            })
        }
        productTableReload();
        return;
    }
    if(obj.field == "amount"){
        if(obj.value*1>obj.data.amountNew){
            layer.msg('不可大于原数量');
            $(this).val(old);
            return;
        }
    }
    let isTaxIncluded = $("#taxIncluded").val()==""?0:$("#taxIncluded").val();//是否含税  1 含税  2 不含税
    let modulus = 1;//含税系数
    if(isTaxIncluded==1){
        modulus=1.13
    }
    //金额
    if (obj.field == "amount" || obj.field == "price" || obj.field == "priceSubtotal" || obj.field == "costPrice"
        || obj.field == "otherPrice" || obj.field == "untaxedPrice" || obj.field == "untaxedPriceSubtotal") {
        if(obj.value<0){
            layer.msg('请输入非负数');
            $(this).val(old);
            obj.update({
                costPrice:old,
            })
            return;
        }
        obj.data.costPrice = obj.data.costPrice?obj.data.costPrice:0.0000;
        if(obj.field == "costPrice"){
            let price = getProductPriceByProductCode(obj.data.productNo, obj.data.specNo);
            if(!isEmpty(price)){
                if(obj.value > price){
                    layer.msg('不能大于产品排价');
                    $(this).val(old);
                    obj.update({
                        costPrice:old,
                    })
                    return;
                }
            }
        }
        obj.data.otherPrice = obj.data.otherPrice?obj.data.otherPrice:0.0000;
        obj.data.amount = obj.data.amount?obj.data.amount:0.00;
        let price = 0.0000;
        if(obj.data.amount==0){
            price = obj.data.costPrice;
        }else{
            price = (Number(obj.data.costPrice)+Number(obj.data.otherPrice/obj.data.amount)).toFixed(6);
        }
        obj.data.price = price;
        obj.data.priceSubtotal = (obj.data.amount*price).toFixed(2);
        // obj.data.upFlag = true;//修改的数据
        obj.update({
            // costPrice:obj.data.costPrice,
            // upFlag:obj.data.upFlag,
            price:obj.data.price,
            priceSubtotal:obj.data.priceSubtotal,
            untaxedPrice:(obj.data.price/modulus).toFixed(4),
            untaxedPriceSubtotal:(obj.data.amount*price/modulus).toFixed(2),
        })

        //获取产品明细金额小计作为采购总额
        let purchaseTotalPrice = getPurchaseTotalPrice();
        //定金比例
        let earnestRate = $("#earnestRate").val();
        //采购总额
        $("#purchaseTotalPrice").val(purchaseTotalPrice);
        //定金金额 = 采购总额*定金比例/100
        let earnestMoney = 0;
        if(!isEmpty(earnestRate) && !isEmpty(purchaseTotalPrice)){
            earnestMoney = new BigNumber(purchaseTotalPrice).multipliedBy(new BigNumber(earnestRate)).dividedBy(100).dp(4, BigNumber.ROUND_HALF_UP).toString();
        }
        $("#earnestMoney").val(earnestMoney);
        //表单重载
        productTableReload();
        form.render('select');
    }

    /**
     * 获取产品明细金额小计
     */
    function getPurchaseTotalPrice() {
        let purchaseTotalPrice = 0;
        let detailData = table.cache["storageproductstableid"];
        for(let i in detailData){
            let priceSubtotal = detailData[i]["priceSubtotal"];
            if(!isEmpty(priceSubtotal)){
                purchaseTotalPrice = new BigNumber(purchaseTotalPrice).plus(new BigNumber(priceSubtotal));
            }
        }
        return purchaseTotalPrice.dp(2, BigNumber.ROUND_HALF_UP).toString();
    }

    if (obj.field == "grossWeight" || obj.field == "grossSubtotal"
        || obj.field == "netWeight" || obj.field == "netSubtotal"
        || obj.field == "volume" || obj.field == "trayNumber"
        || obj.field == "trayNumber" || obj.field == "trayCapacity"
        || obj.field == "numberOfPiece" || obj.field == "qty"
        || obj.field == "outPackLength" || obj.field == "outPackWidth"
        || obj.field == "outPackHeight" || obj.field == "outPackSize"
        || obj.field == "outPackNum") {
        if(!isNumber(obj.value)){
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        if(obj.value=="0"){
            layer.msg('请输入非零数');
            $(this).val(old);
            return;
        }
        if(obj.field == "trayNumber"){
            obj.update({
                trayCapacity:(obj.data.amount/obj.data.trayNumber).toFixed(2),
            })
        }
        if(obj.field == "trayCapacity"){
            obj.update({
                trayNumber:(obj.data.amount/obj.data.trayCapacity).toFixed(2),
            })
        }

        if(obj.field == "numberOfPiece"){
            obj.update({
                qty:(obj.data.amount/obj.data.numberOfPiece).toFixed(2),
            })
        }
        if(obj.field == "qty"){
            obj.update({
                numberOfPiece:(obj.data.amount/obj.data.qty).toFixed(2),
            })
        }

        obj.update({
            grossSubtotal:(obj.data.amount*obj.data.grossWeight).toFixed(2),
            netSubtotal:(obj.data.amount*obj.data.netWeight).toFixed(2),
        })
    }


});

//监听素材供应商下拉框
form.on("select(materialSupplierSelect_filter)", function (data) {
    let elem = data.othis.parents("tr");
    let dataindex = elem.attr("data-index");
    let tabledata = table.cache["storageproductstableid"];
    $.each(tabledata, function (index, value) {
        if (value.LAY_TABLE_INDEX == dataindex) {
            tabledata[index]["materialSupplier"] = data.value;
        }
    });
});

//监听付款类型下拉框
form.on("select(paymentTypeFilter)", function (data) {
    if (data.value === "") {
        return;
    }
    //设置定金比例、定金金额
    setEarnestMoney(data.value);
});

//设置定金比例、定金金额
function setEarnestMoney(code){
    let earnestRate = 0;
    if (code === "1" || code === "9") {
        //定金比例100%
        earnestRate = 100;
    } else if (code === "2" || code === "3") {
        //定金比例30%
        earnestRate = 30;
    }
    $("#earnestRate").val(earnestRate);

    let purchaseTotalPrice = $("#purchaseTotalPrice").val() ? $("#purchaseTotalPrice").val() : 0.0000;
    //定金金额
    let earnestMoney = (purchaseTotalPrice * earnestRate / 100).toFixed(4);
    $("#earnestMoney").val(earnestMoney);
}


//付款账期
$("#paymentTime").on("input",function(e){
    let paymentTime = e.delegateTarget.value;
    let $tr = $('#storageproducts').next().find('tbody tr [data-field="payTime"] div');
    $tr.each(function () {
        $(this).text(paymentTime)
    })
});

//定金比例
let earnestRateMax = 100.00;//定金比例最大值
$("#earnestRate").on("input",function(e){
    let purchaseTotalPrice = $("#purchaseTotalPrice").val()?$("#purchaseTotalPrice").val():0.0000;
    let earnestRate = e.delegateTarget.value;
    let earnestMoney = 0;
    if(earnestRate>earnestRateMax){
        layer.msg('定金比例不可大于100');
        $("#earnestRate").val(earnestRateMax);
        earnestMoney = purchaseTotalPrice;
    }else{
        earnestMoney = (purchaseTotalPrice*earnestRate/100).toFixed(4);
    }
    $("#earnestMoney").val(earnestMoney);
});

//定金金额
$("#earnestMoney").on("input",function(e){
    let purchaseTotalPrice = $("#purchaseTotalPrice").val()?$("#purchaseTotalPrice").val():0.0000;
    let earnestMoney = e.delegateTarget.value;
    let earnestRate = (earnestMoney/purchaseTotalPrice*100).toFixed(4);
    if(earnestRate>earnestRateMax){
        layer.msg('生成的定金比例不可大于100');
        $("#earnestMoney").val(0);
        return ;
    }
    $("#earnestRate").val(earnestRate);
});

form.on("select(supplierFilter)", function (data) {
    let text = $('#supplierCode option:selected').text()
    $("#supplierName").val(text);
    $.each(supplierList, function (index, item){
        if(data.value==item.code){
            form.val("editor-form", {
                "paymentType": item.paymentType,
            });
            //设置定金比例、定金金额
            setEarnestMoney(item.paymentType);
        }
    })
    selectAddress(data.value);

    //是否含税
    let taxIncluded = $("#taxIncluded").val();
    if(isEmpty(taxIncluded)){
        return;
    }
    //更新产品单价
    updateProductPriceBySupplier(data.value, taxIncluded);
});

function updateProductPriceBySupplier(supplierCode, taxIncluded){
    //获取备选供应商
    let alternative = [];
    $.ajax({
        url:"offer/getAlternativeSupplierList?supplierCode=" + supplierCode,
        async:false,
        success:function(data){
            if(data.status == 200){
                alternative = data.data;
            }
        }
    });
    //获取产品明细
    let productsList = table.cache["storageproductstableid"];
    for(let i in productsList){
        //产品编码
        let productCode = productsList[i]["productNo"];
        //规格编码
        let specNo = productsList[i]["specNo"];
        if(isEmpty(alternative) || alternative.length === 0){
            //不在备选供应商,产品单价默认未0
            productsList[i]["costPrice"] = 0;
        }
        let isFindFlag = false;
        for(let j in alternative){
            let flag = alternative[j]["productCode"] === productCode && alternative[j]["specNo"] === specNo
            if(flag){
                isFindFlag = true;
                switch (taxIncluded) {
                    case "1":
                        //含税出厂价
                        productsList[i]["costPrice"] = alternative[j]["taxIncludedPrice"];
                        break;
                    case "2":
                        //未税出厂价
                        productsList[i]["costPrice"] = alternative[j]["untaxedPrice"];
                        break;
                    case "3":
                        //含税FOB价
                        productsList[i]["costPrice"] = alternative[j]["taxIncludedFob"];
                        break;
                    case "4":
                        //未税FOB价
                        productsList[i]["costPrice"] = alternative[j]["untaxedFob"];
                        break;
                }
            }

        }
        if(!isFindFlag){
            //不在备选供应商,产品单价默认未0
            productsList[i]["costPrice"] = 0;
        }

    }
    table.reload('storageproductstableid', {data:productsList});

}

//获取该供应商对应的产品单价
function getProductPriceByProductCode(productCode, specNo){
    let price = 0;
    //供应商编码
    let supplierCode = $("#supplierCode").val();
    if(isEmpty(supplierCode)){
        return price;
    }
    //是否含税
    let taxIncluded = $("#taxIncluded").val();
    if(isEmpty(taxIncluded)){
        return price;
    }
    //获取备选供应商
    let alternative = [];
    $.ajax({
        url:"offer/getAlternativeSupplierList?supplierCode=" + supplierCode,
        async:false,
        success:function(data){
            if(data.status == 200){
                alternative = data.data;
            }
        }
    });
    if(isEmpty(alternative) || alternative.length === 0){
        //不在备选供应商,产品单价默认未0
        return price;
    }
    for(let j in alternative){
        let flag = alternative[j]["productCode"] === productCode && alternative[j]["specNo"] === specNo
        if(flag){
            switch (taxIncluded) {
                case "1":
                    //含税出厂价
                    price = alternative[j]["taxIncludedPrice"];
                    break;
                case "2":
                    //未税出厂价
                    price = alternative[j]["untaxedPrice"];
                    break;
                case "3":
                    //含税FOB价
                    price = alternative[j]["taxIncludedFob"];
                    break;
                case "4":
                    //未税FOB价
                    price = alternative[j]["untaxedFob"];
                    break;
            }
        }

    }
    return price;
}
// 是否含税
form.on("select(taxFilter)", function (data) {
    /*let tableData = table.cache["storageproductstableid"];
    $.each(tableData, function (index, value) {
        value.costPrice = data.value=="1"?value.taxedCostPrice:value.untaxedCostPrice
        tableData[index]["costPrice"] = Number(value.costPrice).toFixed(4);
    });
    table.reload('storageproductstableid',tableData);*/
    let supplierCode = $("#supplierCode").val();
    if(isEmpty(supplierCode)){
        return;
    }
    if(isEmpty(data.value)){
        return;
    }
    //更新产品单价
    updateProductPriceBySupplier(supplierCode, data.value);
});

form.on("select(colourSelect_filter)", function (data) {
    let elem = data.othis.parents("tr");
    let dataIndex = elem.attr("data-index");
    let tableData = table.cache["storageproductstableid"];
    $.each(tableData, function (index, value) {
        if (value.LAY_TABLE_INDEX == dataIndex) {
            tableData[index]["colour"] = data.value;
        }
    });
});
form.on("select(unitSelect_filter)", function (data) {
    let elem = data.othis.parents("tr");
    let dataIndex = elem.attr("data-index");
    let tableData = table.cache["storageproductstableid"];
    $.each(tableData, function (index, value) {
        if (value.LAY_TABLE_INDEX == dataIndex) {
            tableData[index]["unit"] = data.value;
        }
    });
});

form.on("select(complaintUnitSelect)", function (data) {
    let complaintUnitCode = data.value;
    let text = $('#companyCode option:selected').text()
    $("#companyName").val(text);
    let selectCode = 0;
    if(id==""){
        selectCode=0;
    }
    bankSelect(complaintUnitCode,selectCode);
});

form.on("select(executorFilter)", function (data) {
    $("#executorCode").val($('#executor option:selected').val());
    $("#executorName").val($('#executor option:selected').text());
});
form.on("select(salesmanFilter)", function (data) {
    $("#salesmanCode").val($('#salesman option:selected').val());
    $("#salesmanName").val($('#salesman option:selected').text());
});

form.on("select(currencyFilter)", function (data) {
    let usdRate = 0;
    $.each(currencyList, function (index, item) {
        if(data.value == "usd-001"){
            usdRate = 1;
            return;
        }else if (data.value == item.code){
            usdRate = item.exchangeRate;
            return;
        }
    })
    form.val("editor-form", {
        "usdRate": usdRate,
    });
});

//产品明细单个删除
table.on('tool(storageproductstable)', function (obj) {
    let data = obj.data;
    let oldData =  table.cache["storageproductstableid"];
    if (obj.event === 'del') {
        layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
            for(let i in oldData){
                if(oldData[i].tempId == data.tempId){
                    oldData.splice(i, 1);
                    table.reload('storageproductstableid',{data : oldData});
                    break;
                }
            }
            layer.msg("删除成功", {icon: 6});
            reloadCBSelect();
            layer.close(index);
        });
    }
});

table.on('toolbar(storageproductstable)', function (obj) {
    let checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        //导入销售成品
        case 'salesoffinished':
            layer.open({
                type: 2,
                area: $(window).width() < 458 ? "['100%', '100%']" : ['95%', '95%'],
                content: 'views/jsp/ExportBusiness/tpl/salesoffinished.jsp'
            });
            break;
        //导入备货成品
        case 'stockupfinished':
            layer.open({
                type: 2,
                area: $(window).width() < 458 ? "['100%', '100%']" : ['95%', '95%'],
                content: 'views/jsp/ExportBusiness/tpl/stockupfinished.jsp'
            });
            break;
        //导入备货配件
        case 'stockupaccessories':
            layer.open({
                type: 2,
                area: $(window).width() < 458 ? "['100%', '100%']" : ['95%', '95%'],
                content: 'views/jsp/ExportBusiness/tpl/stockupaccessories.jsp'
            });
            break;
        //导入销售配件
        case 'salesaccessories':
            layer.open({
                type: 2,
                area: $(window).width() < 458 ? "['100%', '100%']" : ['95%', '95%'],
                content: 'views/jsp/ExportBusiness/tpl/salesaccessories.jsp'
            });
            break;
        //导入产品库信息
        case 'newSample':
            let oldData = table.cache["storageproductstableid"];
            let tempId = GenNonDuplicateID(3) + (oldData.length + 1);
            let newData = {
                "tempId": tempId,
                "productNo" : "",
                "costPrice" : 0,
                "grossWeight" : 0,
                "grossSubtotal" : 0,
                "netWeight" : 0,
                "netSubtotal" : 0,
                "volume" : 0,
                "priceSubtotal" : 0,
                "price" : 0
            };
            oldData.push(newData);
            table.reload('storageproductstableid', {data: oldData});
            break;
        case 'del':
            let data = checkStatus.data, delList = [];
            data.forEach(function (n, i) {
                delList.push(n.tempId);
            });
            if (delList != '') {
                layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                    let cbList = table.cache["storageproductstableid"];
                    for (var i = 0; i < cbList.length; i++) {
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("storageproductstableid", {
                        data: cbList,
                    });
                    layer.msg('删除成功');
                })
            } else {
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});
//---费用
table.render({
    elem: '#cost'
    , data: []
    , toolbar: '#costtoolbar'
    , cols: [[
        {checkbox: true, fixed: true}
        , {field: 'costtype', title: '费用类型', templet: '#costtypeselect'}
        , {field: 'amount', title: '金额', event: 'amount', edit: 'text'}
        , {field: 'descr', title: '备注说明', edit: 'text'}
    ]]
    , id: 'costtableid'
    , height: 380
    , page: true
});
table.on('edit(costtable)', function (obj) {
    var old = $(this).prev().text();//旧值
    //判断数据类型 ,,,,,,,
    if ((obj.field == "amount") && !isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);
        return;
    }
});
form.on("select(costtypeselect_filter)", function (data) {
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["costtableid"];
    $.each(tabledata, function (index, value) {
        if (value.LAY_TABLE_INDEX == dataindex) {
            tabledata[index]["costtype"] = data.value;
        }
    });
});

table.on('toolbar(costtable)', function (obj) {
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    switch (obj.event) {
        case 'new':
            var oldData = table.cache["costtableid"];
            var data1 = {"id": oldData.length + 1, costtype: "", amount: "", descr: ""};
            oldData.push(data1);
            table.reload('costtableid', {data: oldData});
            break;
        case 'del':
            var data = checkStatus.data, delList = [];
            data.forEach(function (n, i) {
                delList.push(n.id);
            });
            if (delList != '') {
                layer.confirm('确定删除所选项吗？', function (index) {
                    var cbList = table.cache["costtableid"];
                    for (var i = 0; i < cbList.length; i++) {
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined" && item == cbList[i].id) {
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("costtableid", {
                        data: cbList,
                    });
                    layer.msg('删除成功');
                })
            } else {
                layer.msg('请选择需要删除的行');
            }
            break;
    }
    ;
});


//---附件
table.render({
    elem: '#attachment'
    , data: fileList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        // {field: 'fileName', title: '文件名称', fixed: true,style:"overflow:hidden"},
        {field: 'wjName', title: '文件名称', fixed: true,style:"overflow:hidden", event: "wjname"},
        {field: 'fileUrl', title: '文件路径', fixed: true,style:"overflow:hidden"},
        {field: 'fileType', title: '文件类型', fixed: true},
        {field: 'fileSize', title: '文件大小(KB)', fixed: true},
        {field: 'fileExecutor', title: '操作员', fixed: true,
            templet: function(data) {
                let name = "";
                $.each(executorList, function(index, item) {
                    if (data.fileExecutor==item.code){
                        name = item.name;
                        return ;
                    }
                });
                return name;
            }
        },
        {field: 'fileUploadTime', title: '上传时间', fixed: true,
            templet: function(d) {
                return layui.util.toDateString(d.createTime,"yyyy-MM-dd");
            }
        },
        {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'},
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
});
upload.render({
    elem: '#uploadfile'
    , url: 'ftp/uploadFile'
    , field: 'uploadify'
    , accept: 'file'
    , data:{"fileType":"purchase"}
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var newfilename = "";
            if (ispd(wjCatalogCode, file.name)) {
                // newfilename = getFileName(file.name);
                // layer.msg("此目录下已存在重名的文件，已自动对本文件进行了重命名！");
                layer.confirm('已存在同名的文件，是否覆盖？', function (index) {
                    layer.close(index);
                });
            }
            if (newfilename != "") {
                var obj = {};
                obj.code = index;
                obj.name = newfilename;
                fileList.push(obj);
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + newfilename + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    // fileListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    var fileListIns = [];
                    for (var i = 0; i < fileList.length; i++) {
                        if (index != fileList[i].code) {
                            fileListIns.push(fileList[i]);
                        }
                    }
                    fileList = fileListIns;
                });

                $("#uploadlist").append(tr);
            }else{
                var obj = {};
                obj.code = index;
                obj.name = file.name;
                // fileList.push(obj);
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    // fileListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    var fileListIns = [];
                    for (var i = 0; i < fileList.length; i++) {
                        if (index != fileList[i].code) {
                            fileListIns.push(fileList[i]);
                        }
                    }
                    fileList = fileListIns;
                });

                $("#uploadlist").append(tr);
            }
        });
    }
    , done: function (res, index, upload) {
        var filename = "";
        for (var i = 0; i < uploadlist.length; i++) {
            if (uploadlist[i].code == index) {
                filename = uploadlist[i].name;
                break;
            }
        }
        if (res.data.length > 0) {
            var files = res.data;
            var filepaths = [];
            for (var i = 0; i < files.length; i++) {
                var obj = {};
                obj.fileName = files[i].fileName;
                obj.ftpPath = files[i].ftpPath;
                filepaths.push(obj);
            }
            if (savefile(filepaths, filename, wjCatalogCode)) {
                let oldData = fileList;
                let newData = [];
                let num = oldData.length+1;
                for(let i in files){
                    let newFile = {};
                    // fileList[i].tempId = num;
                    newFile.fileName = files[i].fileName;
                    newFile.wjName = files[i].originalFileName;
                    newFile.fileUrl = files[i].ftpPath;
                    newFile.fileSize = (this.files[index].size / 1024).toFixed(1);
                    newData.push(newFile);
                    num++;
                }
                oldData.push.apply(oldData, newData);
                fileList = oldData;
                table.reload('attachmenttableid', {data:fileList});
            }

            var tr = $("#uploadlist").find('tr#upload-' + index), tds = tr.children();
            tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
            tds.eq(3).html(''); //清空操作
            return delete this.files[index]; //删除文件队列已经上传成功的文件
        }
        /* if (res.files.file) { //上传成功
             var tr = $("#uploadlist").find('tr#upload-' + index)
                 , tds = tr.children();
             tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
             tds.eq(3).html(''); //清空操作
             return delete this.files[index]; //删除文件队列已经上传成功的文件
         }*/
        this.error(index, upload);
    }
    , error: function (index, upload) {
        let tr = $("#uploadlist").find('tr#upload-' + index), tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});

table.on('toolbar(attachmenttable)', function (obj) {
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data : fileList}); //点击关闭刷新表格
                }
            });
            break;
    };
});

table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        downFileLoadNew(data.wjName, data.fileUrl+'/'+data.fileName);
    } else if (obj.event === 'del') {
        layer.confirm('确认删除吗？', function (index) {
            let oldData =  fileList;
            for (let i = 0; i < oldData.length; i++) {
                if (oldData[i].id == obj.data.id) {
                    oldData.splice(i, 1);
                    i--;
                    table.reload('attachmenttableid',{data : oldData});
                    break;
                }
            }
            layer.msg("删除成功", {icon: 6});
            layer.close(index);
        });
    }
    if(obj.event==='wjname'){
        onLineFile(data.fileUrl+'/'+data.fileName);
    }
});

//---操作日志
table.render({
    elem: '#otherwarehouselog'
    , data: logList
    , cols: [[
        {field: 'upType', title: '操作类型',
            templet: function(data) {
                let name = "";
                switch (data.upType){
                    case 1: name = "新增"; break;
                    case 2: name = "删除"; break;
                    case 3: name = "更新"; break;
                }
                return name;
            }
        }
        , {field: 'upModel', title: '修改对象',
            templet: function(data) {
                let name = "";
                switch (data.upModel){
                    case 1: name = "采购主表"; break;
                    case 2: name = "采购产品"; break;
                }
                return name;
            }
        }
        , {field: 'upUser', title: '修改人员：编码'}
        , {field: 'upTime', title: '修改日期',
            templet: function (data){
                return layui.util.toDateString(data.upTime,"yyyy-MM-dd HH:mm:ss")
            }
        }
        , {field: 'upContext', title: '修改内容'}
    ]]
    ,id: 'logtableid'
    ,height: 380
    ,page: false
    ,limit: Number.MAX_VALUE
});

function hoverOpenImg() {
    let img_show = null; // tips提示
    $("body").delegate("td img", "mouseover", function () {
        let img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
        img_show = layer.tips(img, this, {
            tips: [2, 'rgba(41,41,41,.5)']
            , area: ['160px']
        });
    });
    $("body").delegate("td img", "mouseout", function () {
        layer.close(img_show);
    });
}

function isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}


function queryById() {
    $.ajax({
        type: 'POST',
        url: 'purchase/selectByKey/' + id,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        success: function (res) {
            if (res.status == 200) {
                if(res.data){
                    let supplierCode = res.data.supplierCode;
                    //设置联系人
                    setContactPerson(supplierCode);
                    form.val("editor-form", {
                        "purchaseOrderNo": res.data.purchaseOrderNo,
                        "newBillNo": res.data.purchaseOrderNo,
                        "purchaseType": res.data.purchaseType,
                        "supplierCode": res.data.supplierCode,
                        "supplierName": res.data.supplierName,
                        "contactPerson": res.data.contactPerson,
                        "contactEmail": res.data.contactEmail,
                        "salesContractNo": res.data.salesContractNo,
                        "companyCode": res.data.companyCode,
                        "companyName": res.data.companyName,
                        "signTime": res.data.signTime,
                        "bank": res.data.bank,
                        "deliverDate": res.data.deliverDate,
                        "deliverAddress": res.data.deliverAddress,
                        "currency": res.data.currency,
                        "rmbRate": res.data.rmbRate,
                        "usdRate": res.data.usdRate,
                        "purchaseTotalPrice": res.data.purchaseTotalPrice,
                        "executorCode": res.data.executorCode,
                        "salesmanCode": res.data.salesmanCode,
                        "executorName": res.data.executorName,
                        "salesmanName": res.data.salesmanName,
                        "remark": res.data.remark,
                        "sn": res.data.sn,
                        "paymentType": res.data.paymentType,
                        "paymentTime": res.data.paymentTime,
                        "earnestRate": res.data.earnestRate,
                        "earnestMoney": res.data.earnestMoney,
                        "totalApplication": res.data.totalApplication,
                        "invoiceStatus": res.data.invoiceStatus,
                        "taxIncluded": res.data.taxIncluded,
                        "createTime":res.data.createTime,
                        "editTime":res.data.editTime,
                        "boxStatus": res.data.boxStatus,
                        "customerLevelCode" : res.data.customerLevelCode,
                        "customerLevelName" : res.data.customerLevelName,
                        "modeOfTrade" : res.data.modeOfTrade
                    });
                    laydate.render({
                        elem: '#deliverDate',
                        type: 'date',
                        value: new Date(res.data.deliverDate),
                    });
                    laydate.render({
                        elem: '#signTime',
                        type: 'date',
                        value: new Date(res.data.signTime),
                    });
                    bankSelect(res.data.companyCode,res.data.bank);
                    let productListData = selectProductByPuId(id);
                    for(let i in productListData){
                        productListData[i]["tempId"] = productListData[i]["id"];
                        productList.push(productListData[i]);
                    }
                    table.reload('storageproductstableid',{data : productList});
                    fileList = selectFileByPuId(id);
                    table.reload('attachmenttableid',{data : fileList});
                    selectLogByPuId(id);
                    table.reload('logtableid',{data : logList});
                    $("#whetherCreditGuarantee").val(res.data.whetherCreditGuarantee);
                    $("#creditGuaranteeAmount").val(res.data.creditGuaranteeAmount);
                }else{
                    layer.msg("初始化失败!");
                }
            } else {
                layer.msg("初始化失败!");
            }
        },
        error: function (data) {
            layer.msg("初始化失败!");
        }
    });
}

//产品
function selectProductByPuId(puId) {
    let obj = [];
    $.ajax({
        async: false,
        type: 'POST',
        url: 'purchase/selectProductByPuId/'+puId,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        success: function (res) {
            if (res.status == 200) {
                if(res.data.length>0){
                    obj = res.data;
                }else{
                    // layer.msg(res.msg, {icon : 0})
                }
            }else{
                layer.msg("产品初始化失败!");
            }
        },
        error: function (data) {
            layer.msg("产品初始化失败!");
        }
    });
    return obj;
}
//附件
function selectFileByPuId(puId) {
    let obj = [];
    $.ajax({
        async: false,
        type: 'POST',
        url: 'purchase/selectFileByPuId/'+puId,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        success: function (res) {
            if (res.status == 200) {
                if (res.data.length>0){
                    obj = res.data;
                }else{
                    // layer.msg("暂无附件数据",{icon:3});
                }
            }else{
                // layer.msg(res.msg,{icon:3});
            }
        },
        error: function (data) {
            layer.msg("附件初始化失败!");
        }
    });
    return obj;
}

//附件
function selectBlueprintFileByCode(proCode,specNo) {
    let params = {
        productNo : proCode,
        specNo : specNo,
    };
    let obj = [];
    $.ajax({
        async: false,
        type: 'POST',
        data: JSON.stringify(params),
        url: 'purchase/selectBlueprintFileByCode',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        success: function (res) {
            if (res.status == 200) {
                if (res.data.length>0){
                    obj = res.data;
                    $.each(res.data,function (index,item) {
                        item.id = "";
                        fileList.push(item);
                    })
                    table.reload('attachmenttableid',{data : obj});
                    form.render('select');
                }else{
                    // layer.msg("暂无附件数据",{icon:3});
                }
            }else{
                // layer.msg(res.msg,{icon:3});
            }
        },
        error: function (data) {
            layer.msg("附件初始化失败!");
        }
    });
    return obj;
}

//日志
function selectLogByPuId(puId) {
    $.ajax({
        async: false,
        type: 'POST',
        url: 'purchase/selectLogByPuId/' + puId,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        success: function (res) {
            if (res.status == 200) {
                logList = res.data;
            }
        },
        error: function (data) {
            layer.msg("日志初始化失败!");
        }
    });
}

function insert(data) {
    let tf = false;
    $.ajax({
        type: 'POST',
        data: JSON.stringify(data),
        url: 'purchase/insert',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if (res.data>0) {
                    tf = true;
                    layer.msg("保存成功!",{icon: 6});
                } else {
                    layer.msg(res.msg+"保存失败", {icon: 5});
                }
            } else {
                layer.msg(res.msg+"保存失败",{icon: 7});
            }
        },
        error: function (data) {
            layer.msg("保存失败!",{icon: 2});
        }
    });
    return tf;
}

function update(data) {
    let tf = false;
    $.ajax({
        type: 'POST',
        data: JSON.stringify(data),
        url: 'purchase/update',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if (res.data>0) {
                    tf = true;
                    layer.msg("保存成功!",{icon: 6});
                } else {
                    layer.msg(res.msg+"保存失败", {icon: 5});
                }
            } else {
                layer.msg(res.msg,{icon: 7});
            }
        },
        error: function (data) {
            layer.msg("保存失败!",{icon: 2});
        }
    });
    return tf;
}

//按签约公司编号 查询对应银行
function bankSelect(code,selectCode){
    $("#bank").empty();
    $.ajax({
        url: "bank/selectByCompanyCode",
        data: {"CompanyCode":code},
        success: function (res) {
            if (res.status == 200) {
                $.each(res.data, function (index, item) {
                    bankList = res.data;
                    $("#bank").append(new Option(item.bankname, item.bankcode));
                });
                $.each(res.data,function (i,n) {
                    let isExist = false;
                    $.each(bankList,function (j,m) {
                        if(m.code==n.bankCode){
                            isExist = true;
                            return;
                        }
                    })
                    if(!isExist){
                        bankList.push({code:n.bankCode,name:n.bankName})
                    }
                })

                if(selectCode!=0){
                    $.each(bankList, function (index, item) {
                        if (item.bankcode==selectCode){
                            $("#bank").val(item.bankcode);
                        }
                    });
                    let bank = $("#bank").val();
                    if(bank==""){
                        $("#bank").append(new Option(selectCode, selectCode));
                        $("#bank").val(selectCode);
                    }
                }
                form.render('select');
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

//重载签约公司和银行
function reloadCBSelect() {
    let companyCode = $("#companyCode").val();
    $("#companyCode").empty();
    complaintUnit.push({code:'',name:''});
    $.each(complaintUnit, function (index, item) {
        if(item){
            $("#companyCode").append(new Option(item.name, item.code));
        }
    });
    $("#companyCode").val(companyCode);
    $("#bankCode").empty();
    bankList.push({code:'',name:''});
    $.each(bankList, function (index, item) {
        $("#bankCode").append(new Option(item.name, item.code));
    });
    form.render('select');
}

//获取文件目录下所有的文件名
    function ispd(wjCatalogCode, filename) {
        /* fileNames=[];*/
        var cun = false;
        $.ajax({
            type: 'get',
            //  url : 'resource/getTree',
            data: {"wjCatalogCode": wjCatalogCode, "name": filename},
            url: 'wjinfo/ispd',
            dataType: "json",
            /*  contentType: 'application/json',*/
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    cun = da.data == 0 ? false : true;

                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return cun;
        // return obj;
    }

    function getFileName(filename) {
        /* fileNames=[];*/
        var cun = "";
        $.ajax({
            type: 'get',
            //  url : 'resource/getTree',
            data: {"filename": filename},
            url: 'wjinfo/getFileName',
            dataType: "json",
            /*  contentType: 'application/json',*/
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    cun = da.data;

                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return cun;
        // return obj;
    }

    //判断文件名是否重复
    function iscf(filename) {
        var tf = false;
        for (var i = 0; i < fileNames.length; i++) {
            if (filename == fileNames[i]) {
                tf = true;
                break;
            }
        }
        return tf;
    }

    //保存上传的文件
    function savefile(filepaths, filename, wjCatalogCode) {
        var tf = false;
        $.ajax({
            type: 'post',
            data: {
                "files": JSON.stringify(filepaths), "wjCatalogCode": JSON.stringify(wjCatalogCode),
                "name": JSON.stringify(filename)
            },
            url: 'wjinfo/savefile',
            dataType: "json",
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    tf = da.data == 0 ? false : true;
                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return tf;
    }

    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }

    //生成临时id
    function GenNonDuplicateID(randomLength){
        return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
    }

});

